<template>
  <div class="spots-manage">
    <div class="page-header">
      <h1 class="page-title">排行榜管理</h1>
      <el-button type="primary" @click="handleAdd">新增景点</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="景点名称">
          <el-input v-model="searchForm.name" placeholder="请输入景点名称" clearable />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="searchForm.location" placeholder="请输入地点" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe>
        <!-- <el-table-column prop="_id" label="ID" width="80" /> -->
        <el-table-column label="封面" width="200">
          <template #default="{ row }">
            <el-image :src="row.image" :preview-src-list="[row.image]" style="width: 80px; height: 80px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="景点名称" min-width="100" />
        <el-table-column prop="description" label="景点描述" min-width="200" />
        
        <!-- <el-table-column prop="location" label="地点" width="150" /> -->
        <el-table-column prop="score" label="评分" width="100">
          <template #default="{ row }">
            <el-rate :model-value="row.score / 2" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览量" width="100" />
        <el-table-column prop="votes" label="投票数" min-width="100" />
        <el-table-column prop="reviewCount" label="评论数" width="100" />
        <el-table-column prop="likes" label="点赞数" width="100" />

        <el-table-column label="创建时间" width="200" prop="createDate" />
        <el-table-column label="操作" min-width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="景点名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入景点名称" />
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="封面图" prop="image">
          <el-input v-model="formData.image" placeholder="请输入封面图地址" />
          <div v-if="formData.image" style="margin-top: 10px">
            <el-image :src="formData.image" style="width: 200px; height: 200px" fit="cover" />
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入景点描述" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-rate v-model="rateValue" @change="handleRateChange" show-score text-color="#ff9900" />
          <span style="margin-left: 10px; color: #999;">（内部分值：{{ formData.score }}）</span>
        </el-form-item>
        <el-form-item label="特色标签">
          <el-input v-model="formData.tags" placeholder="请输入标签，用逗号分隔" />
        </el-form-item>
        <el-form-item label="门票价格">
          <el-input-number v-model="formData.ticketPrice" :min="0" :precision="2" />
          <span style="margin-left: 10px;">元</span>
        </el-form-item>
        <el-form-item label="开放时间">
          <el-input v-model="formData.openTime" placeholder="例如：8:00-18:00" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSpotsList, createSpot, updateSpot, deleteSpot } from '@/api/admin'

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增景点')
const formRef = ref()
const isEdit = ref(false)
const currentId = ref('')
const rateValue = ref(0)

const searchForm = reactive({
  name: '',
  location: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const formData = reactive({
  name: '',
  location: '',
  image: '',
  description: '',
  score: 0,
  tags: '',
  ticketPrice: 0,
  openTime: ''
})

const rules = {
  name: [{ required: true, message: '请输入景点名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  image: [{ required: true, message: '请输入封面图地址', trigger: 'blur' }],
  score: [{ required: true, message: '请选择评分', trigger: 'change' }]
}

const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getSpotsList(params)
    console.log("排行榜数据", res)
    tableData.value = res.data || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.location = ''
  handleSearch()
}

const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增景点'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '编辑景点'
  currentId.value = row._id
  Object.assign(formData, {
    name: row.name,
    location: row.location,
    image: row.image,
    description: row.description || '',
    score: row.score || 0,
    tags: row.tags || '',
    ticketPrice: row.ticketPrice || 0,
    openTime: row.openTime || ''
  })
  rateValue.value = formData.score / 2
  dialogVisible.value = true
}

const handleRateChange = (value: number) => {
  formData.score = value * 2
}

const handleSubmit = async () => {
  await formRef.value.validate()
  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updateSpot(currentId.value, formData)
      ElMessage.success('更新成功')
    } else {
      await createSpot(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除该景点吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSpot(row._id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    location: '',
    image: '',
    description: '',
    score: 0,
    tags: '',
    ticketPrice: 0,
    openTime: ''
  })
  rateValue.value = 0
}

const formatTime = (timestamp: any) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.spots-manage {
  width: 100%;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>

